var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// 引入WebSocket
const WebSocket = require('ws');

// var gk = require('./routes/GK/index')
var GKRouter = require('./routes/GK/index')
var LCYRouter = require('./routes/LCY/index')
var SSRouter = require('./routes/SS/index')
var WYQRouter = require('./routes/WYQ/index')
var YJLouter = require('./routes/YJL/index')
var YSKRouter = require('./routes/YSK/index')
var LXLRouter = require('./routes/LXL/index')

var app = express();
var cors = require( 'cors' );

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 修改CORS配置，确保正确处理凭证
app.use(cors({
  // 允许任何来源访问，这样局域网内的任何设备都可以连接
  origin: function(origin, callback) {
    callback(null, true); // 允许所有来源
  },
  credentials: true,
  methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  exposedHeaders: ['Authorization'],
  maxAge: 3600
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/upload',express.static(path.join(__dirname,'upload')));
app.use('/uploads', express.static(path.join(__dirname, 'routes', 'uploads')));

app.use('/gk',GKRouter)
app.use('/lcy',LCYRouter)
app.use('/lxl',LXLRouter)
app.use('/ss',SSRouter)
app.use('/yjl',YJLouter)
app.use('/ysk',YSKRouter)
app.use('/wyq',WYQRouter)
// app.use('/renlian', renlianRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// 使用LCY路由的WebSocket服务器设置
module.exports = app;

// 导出setupWebSocketServer函数
module.exports.setupWebSocketServer = LCYRouter.setupWebSocketServer;
